package com.ruoyi.project.monitor.redismonitor.task.impl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.RedisMonitorUtil;
import com.ruoyi.common.utils.RedisMonitorUtil.RedisInfo;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.monitor.redismonitor.domain.RedisMonitor;
import com.ruoyi.project.monitor.redismonitor.service.IRedisMonitorService;
import com.ruoyi.project.monitor.tarsmonitor.task.TarsMonitorTask;
import com.ruoyi.project.monitor.warndistribute.service.IWarnDistributeService;

@Component("redisMonitor")
public class RedisMonitorTaskImpl implements TarsMonitorTask {

	protected static Log logger = LogFactory.getLog(RedisMonitorTaskImpl.class);

	@Autowired
	RuoYiConfig ruoYiConfig;

	@Autowired
	IRedisMonitorService iRedisMonitorService;

	@Autowired
	IWarnDistributeService iWarnDistributeService;

	public void setStatus(RedisMonitor monitor) {

		String resource = monitor.getHost() + ":" + monitor.getPort();

		RedisInfo info = RedisMonitorUtil.get(monitor.getHost(), monitor.getPort().intValue(), monitor.getPassword());
		if (info.isSuccess()) {
			monitor.setStatus(1);
			monitor.setConnectedClients(info.getConnectedClients());
			monitor.setExpires(info.getExpires());
			monitor.setKeys(info.getKeys());
			monitor.setTotalCommandsProcessed(info.getTotalCommandsProcessed());
			monitor.setUsedMemory(info.getUsedMemory());
			monitor.setError("success");
			iWarnDistributeService.onSuccess(resource);
		} else {
			monitor.setStatus(-1);
			monitor.setError(info.getError());
			iWarnDistributeService.onError(resource, monitor.getError());
		}
	}

	@Override
	public void run() {

		if (!ruoYiConfig.isProd()) {
			return;
		}

		RedisMonitor query = new RedisMonitor();
		List<RedisMonitor> list = iRedisMonitorService.selectRedisMonitorList(query);
		list.forEach(item -> {

			setStatus(item);
			item.setLastActiveTime(DateUtils.getNowDate());
			iRedisMonitorService.updateRedisMonitor(item);

		});
	}

}
